Page({
  data: {
    keywords: '',
    // 本页面内的业务子分类（示例：受理、调解、回访）
    categories: [
      { id: 'd1', name: '纠纷受理' },
  // 全局加载状态
  globalLoading: false,
  globalLoadingText: '服务事项加载中...',

  // 显示全局加载
  showGlobalLoading(text = '服务事项加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },
      { id: 'd2', name: '现场调解' },
      { id: 'd3', name: '回访与跟进' }
    ],
    currentCateId: 'd1',
    currentCateName: '',
    filterOptions: [],
    // 事项列表（保持字段与参考页一致：id、cateId、title、desc、dept、online、appoint）
    items: [
      { id: 'md1', cateId: 'd1', title: '矛盾纠纷受理登记', desc: '提交纠纷基本信息并获取受理编号', dept: '综治办', online: true, appoint: false },
      { id: 'md2', cateId: 'd1', title: '人民调解申请', desc: '发起人民调解，提交双方信息与诉求', dept: '综治办', online: true, appoint: true },
      { id: 'md3', cateId: 'd2', title: '调解会议预约', desc: '预约现场/视频调解时间与地点', dept: '人民调解委员会', online: false, appoint: true },
      { id: 'md4', cateId: 'd2', title: '调解协议签署', desc: '在线查看并签署调解协议文本', dept: '人民调解委员会', online: true, appoint: false },
      { id: 'md5', cateId: 'd3', title: '调解结果回访', desc: '回访调解落实情况并反馈满意度', dept: '综治办', online: true, appoint: false }
    ]
  },

  onShow() {
    this.updateCateName()
    this.computeCounts()
    this.generateFilterOptions()
    this.loadFavorites()
    this.applyFilter()
  },

  // 动态生成筛选项（与参考页一致策略）
  generateFilterOptions() {
    const { items, currentCateId, keywords } = this.data;
    const currentItems = keywords ? items : items.filter(it => it.cateId === currentCateId);
    const filterAttrs = [];
    if (currentItems.length > 0) {
      const sampleItem = currentItems[0];
      Object.keys(sampleItem).forEach(key => {
        if (!['id', 'cateId', 'title', 'desc', 'dept'].includes(key) && typeof sampleItem[key] === 'boolean') {
          filterAttrs.push(key);
        }
      });
    }
    const filterOptions = [];
    filterAttrs.forEach(attr => {
      const hasAttrTrue = currentItems.some(item => item[attr] === true);
      if (hasAttrTrue) {
        let name = '';
        switch(attr) {
          case 'online':
            name = '仅在线办理';
            break;
          case 'appoint':
            name = '仅可预约';
            break;
          default:
            name = `仅${attr}`;
        }
        filterOptions.push({ id: attr, name });
      }
    });
    this.setData({ filterOptions });
  },

  // 分类切换
  onTapCate(e) {
    const id = e.currentTarget.dataset.id
    this.setData({ currentCateId: id, keywords: '' })
    this.updateCateName()
    this.applyFilter()
  },

  updateCateName() {
    const cate = this.data.categories.find(c => c.id === this.data.currentCateId)
    this.setData({ currentCateName: cate ? cate.name : '' })
  },

  // 计算各分类数量
  computeCounts() {
    const counts = {}
    this.data.items.forEach(it => {
      counts[it.cateId] = (counts[it.cateId] || 0) + 1
    })
    this.setData({ cateCounts: counts })
  },

  filter: { online: false, appoint: false },
  favorites: {},

  // 加载收藏状态
  async loadFavorites() {
    try {
      const currentUser = require('../../../../utils/auth').getCurrentUser()
      if (!currentUser || !currentUser.userId) {
        this.favorites = {}
        this.setData({ favorites: {} })
        return
      }

      const { getUserFavorites } = require('../../../../api/serviceItems')
      const items = this.data.items || []
      
      // 获取用户收藏列表
      const result = await getUserFavorites(currentUser.userId)
      
      const favorites = {}
      if (result.success && result.data.favorites) {
        // 创建收藏ID集合，便于快速查找
        const favoriteIds = new Set(result.data.favorites.map(fav => fav.serviceItemId))
        
        // 更新收藏状态
        items.forEach(item => {
          favorites[item.id] = favoriteIds.has(item.id)
        })
      } else {
        // 如果获取失败，将所有项目标记为未收藏
        items.forEach(item => {
          favorites[item.id] = false
        })
      }
      
      this.favorites = favorites
      this.setData({ favorites })
    } catch (error) {
      console.error('加载收藏状态失败:', error)
      this.favorites = {}
      this.setData({ favorites: {} })
    }
  },

  // 搜索（全局搜索，不限分类）
  onSearchConfirm(e) {
    this.setData({ keywords: (e.detail.value || '').trim() })
    this.applyFilter()
  },

  // 计算筛选结果
  applyFilter() {
    const { items, currentCateId, keywords, categories } = this.data
    const { online, appoint } = this.filter
    const filteredBase = keywords ? items : items.filter(it => it.cateId === currentCateId)
    const filtered = filteredBase
      .filter(it => !keywords || it.title.indexOf(keywords) >= 0 || it.desc.indexOf(keywords) >= 0)
      .filter(it => (online ? it.online : true))
      .filter(it => (appoint ? it.appoint : true))
    const cateMap = {}
    categories.forEach(c => cateMap[c.id] = c.name)
    this.setData({ filteredItems: filtered, cateMap })
    this.setData({ currentCateName: keywords ? '搜索结果' : (this.data.currentCateName) })
  },

  // 进入事项详情/办理
  onTapItem(e) {
    const id = e.currentTarget.dataset.id
    // 这里可按需映射到具体办理页；暂以提示为主
    const item = (this.data.items || []).find(it => it.id === id)
    if (item && item.appoint && !item.online) {
      wx.showToast({ title: '该事项支持预约到村委办理', icon: 'none' })
    } else if (item && item.online) {
      wx.showToast({ title: '在线办理功能开发中', icon: 'none' })
    } else {
      wx.showToast({ title: '该服务正在完善', icon: 'none' })
    }
  },

  // 切换筛选
  onToggleFilter(e) {
    const type = e.currentTarget.dataset.type
    this.filter[type] = !this.filter[type]
    this.setData({ filter: this.filter })
    this.applyFilter()
  },

  // 收藏
  async onToggleFav(e) {
    const id = e.currentTarget.dataset.id
    const isFavorited = this.favorites[id] || false
    
    const currentUser = require('../../../../utils/auth').getCurrentUser()
    if (!currentUser || !currentUser.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }
    
    try {
      const { addFavorite, removeFavorite } = require('../../../../api/serviceItems')
      let result
      
      if (isFavorited) {
        result = await removeFavorite(id, currentUser.userId)
      } else {
        result = await addFavorite(id, currentUser.userId)
      }
      
      if (result.success) {
        const favs = { ...this.favorites }
        favs[id] = !isFavorited
        this.favorites = favs
        this.setData({ favorites: favs })
        
        wx.showToast({
          title: favs[id] ? '已收藏' : '已取消收藏',
          icon: 'success',
          duration: 1500
        })
      } else {
        wx.showToast({
          title: result.message || (isFavorited ? '取消收藏失败' : '收藏失败'),
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('收藏操作失败:', error)
      wx.showToast({
        title: isFavorited ? '取消收藏失败' : '收藏失败',
        icon: 'none'
      })
    } finally {
            this.hideGlobalLoading();
      }
  }
})


